package com.wujunshen.elasticsearch5;

import com.wujunshen.elasticsearch5.support.Elasticsearch5Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
@Configuration
@EnableConfigurationProperties({ElasticsearchProperties.class, Transport.class})
@ConditionalOnWebApplication
public class Elasticsearch5AutoConfiguration {
    @Resource
    private ElasticsearchProperties elasticsearchProperties;
    @Resource
    private Transport transport;

    @Bean
    public TransportClient esClient() {
        TransportClient esClient = null;
        try {
            Settings settings = Settings.builder()
                    .put("cluster.name", elasticsearchProperties.getClusterName())
                    .put("client.transport.sniff",
                            Boolean.valueOf(elasticsearchProperties.getSniff()))
                    .put("client.transport.ignore_cluster_name",
                            Boolean.valueOf(transport.getIgnoreClusterName()))
                    .put("client.transport.ping_timeout",
                            transport.getPingTimeout())
                    .put("client.transport.nodes_sampler_interval",
                            transport.getNodesSamplerInterval())
                    .build();
            esClient = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new InetSocketTransportAddress(
                            InetAddress.getByName(elasticsearchProperties.getHost()),
                            Integer.valueOf(elasticsearchProperties.getPort())));
        } catch (UnknownHostException e) {
            log.error("Can not connect to elasticsearch: {}",
                    ExceptionUtils.getStackTrace(e));
        }
        return esClient;
    }

    @Bean
    public Elasticsearch5Template esTemplate() {
        return new Elasticsearch5Template();
    }
}